package com.hrsaas.ext.spider.core.url;

import java.net.MalformedURLException;

import com.hrsaas.ext.spider.util.Assert;

/**
 * <p>
 * 功能：自定义url
 * <p>
 * 
 * @author wangxiaoliang@kanzhun.com
 *
 *         2018年8月1日
 */
public final class URL {

	private final Protocol protocol;
	private final String host;
	private final int port;
	private final String path;
	private final Parameters parameters;

	URL(Protocol protocol, String host, int port, String path, Parameters query) {
		this.protocol = protocol;
		this.host = host;
		this.port = port;
		this.path = path;
		this.parameters = query;
	}

	public URL withProtocol(Protocol protocol) {
		if (protocol.equals(this.protocol)) {
			return this;
		}
		return new URL(protocol, host, port, path, parameters);
	}

	public static URLBuilder builder() {
		return new URLBuilder();
	}

	public static URLBuilder builder(Protocol protocol) {
		Assert.notNull("protocol", protocol);
		return new URLBuilder(protocol);
	}

	public static URLBuilder builder(URL startWith) {
		Assert.notNull("startWith", startWith);
		return new URLBuilder(startWith);
	}

	public static URL parse(String url) {
		return URLParser.getURL(url);
	}

	public String getHost() {
		return host;
	}

	public String getPath() {
		return path;
	}

	public int getPort() {
		return port != -1 ? protocol == null ? null : protocol.getDefaultPort() : port;
	}

	public Protocol getProtocol() {
		return protocol;
	}

	public Parameters getParameters() {
		return parameters;
	}

	/**
	 * @return A host and port
	 */
	public HostAndPort getHostAndPort() {
		return new HostAndPort(getHost(), getPort());
	}

	public String getPathAndQuery() {
		StringBuilder sb = new StringBuilder();
		if (path != null) {
			sb.append(path);
		}
		if (this.parameters != null) {
			sb.append(parameters.toString());
		}
		return sb.toString();
	}

	/**
	 * https protocol is security
	 * @return
	 */
	public boolean isSecure() {
		return protocol != null && protocol.isSecure();
	}

	/**
	 * 转换成 java.net.URL
	 * @return java.net.URL
	 */
	public java.net.URL toNetURL() {
		try {
			return new java.net.URL(protocol.getName(), host, protocol.getDefaultPort(), path);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
}
